package org.carota.itext5;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfStamper;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.carota.pdf.PdfConfigurer;
import org.carota.pdf.PdfProcessor;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author : AnWen
 * @version :1.0
 * @email : anwen375@qq.com
 * @since : 2023-03-29 18:48
 */
@Slf4j
@NoArgsConstructor
public class FillPdfTemplateConfigurer extends PdfConfigurer {


    private Map<String, Object> data;
    private BaseFont font;

    public FillPdfTemplateConfigurer(PdfProcessor processor) {
        super(processor);
        try {
            this.font = BaseFont.createFont ("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        } catch (DocumentException | IOException e) {
            log.error ("初始化字体异常: ",e);
            throw new RuntimeException ("初始化字体异常");
        }
    }

    public FillPdfTemplateConfigurer data(Map<String, Object> data) {
        this.data = data;
        return this;
    }

    public FillPdfTemplateConfigurer font(BaseFont font) {
        this.font = font;
        return this;
    }

    public Map<String, Object> getData() {
        return data;
    }

    public BaseFont getFont() {
        return font;
    }

    /**
     * 填充
     */
    @Override
    public void execute() {
        try {

            PdfStamper stamper = processor.getStamper ();
            ArrayList<BaseFont> fontList = new ArrayList<> ();
            fontList.add (font);
            /* 取出报表模板中的所有字段 */
            AcroFields fields = stamper.getAcroFields ();
            fields.setSubstitutionFonts (fontList);

            List<String> keys = new ArrayList<> ();
            Map<String, AcroFields.Item> formFields = fields.getFields ();
            //遍历数据 填充到表单域
            for (String key : data.keySet ()) {
                if (formFields.containsKey (key)) {
                    Object value = data.get (key);
                    fields.setField (key, value.toString ());
                    keys.add (key);
                }
            }
            //遍历表单域  将没有被填充的表单域的值设置为空字符串
            for (String itemKey : formFields.keySet ()) {
                if (!keys.contains (itemKey)) {
                    fields.setField (itemKey, "");
                }
            }

            /* 必须要调用这个，否则文档不会生成的  如果为false那么生成的PDF文件还能编辑，一定要设为true*/
            stamper.setFormFlattening (true);
        } catch (Exception e) {
            log.error ("填充模板失败: ", e);
            throw new RuntimeException ("填充模板失败",e);
        }
    }

    /**
     * 校验参数
     */
    @Override
    protected void checkParams() {
        checkParams("pdf模板填充",data, "data");
    }

    @Override
    public int getOrder() {
        return 30;
    }
}
